package com.sixmac.controller;

import com.sixmac.common.exception.GeneralExceptionHandler;
import com.sixmac.controller.common.CommonController;
import com.sixmac.core.Constant;
import com.sixmac.core.bean.Result;
import com.sixmac.entity.SysUser;
import com.sixmac.service.OperaService;
import com.sixmac.service.SysUserService;
import com.sixmac.service.AppUserService;
import com.sixmac.utils.IdenCode;
import com.sixmac.utils.Md5Util;
import com.sixmac.utils.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangbin on 2015/7/29.
 */
@Controller
@RequestMapping(value = "")
public class IndexController extends CommonController {

    public static Integer loginCount = 0;

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private OperaService operaService;

    @RequestMapping(value = "/login")
    public String login(String error,
                        ModelMap model) {
        if (StringUtils.isNotBlank(error)) {
            model.addAttribute("error", error);
        }
        return "登录";
    }

    @RequestMapping(value = "/login/register")
    public String register(HttpServletRequest request) {
        request.getSession().removeAttribute("error");
        return "注册";
    }

    @RequestMapping(value = "/login/check")
    public String checkLogin(String account,
                             String password,
                             HttpServletRequest request,
                             String code,
                             ModelMap model) {
        HttpSession session = request.getSession();

        // 验证码
        if (!code.equalsIgnoreCase((String) request.getSession().getAttribute("code"))) {
            model.addAttribute("error", "验证码不正确");
            return "redirect:/login";
        }

        // 管理员
        SysUser sysUser = appUserService.sysUserLogin(session, account, Md5Util.md5(password));
        if (null != sysUser) {
            // 记录登录操作
            operaService.addOperaInfo(request, "登录系统");

            // 增加今日访问人数和在线人数
            loginCount += 1;

            return "redirect:/backend/dashboard";
        }

        model.addAttribute("error", "用户名或密码错误!");
        return "redirect:/login";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        appUserService.logOut(request);
        return "登录";
    }

    @RequestMapping(value = "/")
    public String index() {
        return "redirect:/backend/dashboard";
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/login/getIdenCode")
    public void getIdenCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 生成验证码
            IdenCode.getIdenCode(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测当前登录人旧密码是否正确
     *
     * @param request
     * @param response
     * @param oldPwd
     */
    @RequestMapping("/check/oldPwd")
    public void checkOldPwd(HttpServletRequest request,
                            HttpServletResponse response,
                            String oldPwd) {
        Integer id = (Integer) request.getSession().getAttribute(Constant.CURRENT_USER_ID);

        SysUser sysUser = sysUserService.getById(id);
        checkOldPwd(oldPwd, sysUser.getPassword(), response);
    }

    /**
     * 检测旧密码是否正确
     *
     * @param oldPwd
     * @param pwd
     * @param response
     */
    private void checkOldPwd(String oldPwd, String pwd, HttpServletResponse response) {
        Map<String, String> result = new HashMap<String, String>();
        if (!pwd.equals(Md5Util.md5(oldPwd))) {
            result.put("error", "旧密码不正确!");
            WebUtil.print(response, result);
        } else {
            result.put("ok", "");
            WebUtil.print(response, result);
        }
    }

    @RequestMapping("/modifyPwd")
    public void modifyPwd(HttpServletRequest request, HttpServletResponse response,
                          String oldPwd,
                          String newPwd) {
        SysUser sysUser = null;
        Boolean flag = false;

        try {
            Integer loginId = (Integer) request.getSession().getAttribute(Constant.CURRENT_USER_ID);

            // 管理员
            sysUser = sysUserService.getById(loginId);
            if (null != sysUser) {
                if (sysUser.getPassword().equals(Md5Util.md5(oldPwd))) {
                    sysUser.setPassword(Md5Util.md5(newPwd));
                    sysUserService.update(sysUser);

                    flag = true;
                }
            }

            if (null != sysUser) {
                if (flag) {
                    // 记录操作
                    if (null != sysUser) {
                        operaService.addOperaInfo(request, "修改密码");
                    }

                    // 增加今日访问人数和在线人数
                    loginCount += 1;

                    appUserService.logOut(request);
                    WebUtil.print(response, new Result(true).msg("修改密码成功！请重新登录！"));
                } else {
                    WebUtil.print(response, new Result(false).msg("旧密码错误，修改密码失败！"));
                }
            } else {
                WebUtil.print(response, new Result(false).msg("当前用户未登录！"));
            }
        } catch (Exception e) {
            GeneralExceptionHandler.log("修改密码失败", e);
            WebUtil.print(response, new Result(false).msg("修改密码失败！"));
        }
    }

}
